﻿using B.S.Passport.Domain;
using B.S.Passport.ErrorCode;
using B.S.Passport.Infacetrue;
using B.S.Passport.Write.API.Application.PurchaseOrdername;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Passport.Read.API.Application.Commandhander123
{
    public class PurchaseOrderCommandHander : IRequestHandler<PurchaseOrderCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<ProductModel> _productModelRepository;
        private readonly IBaseRepository<PurchaseOrder> _purchaseOrderRepository;

        public PurchaseOrderCommandHander(IBaseRepository<ProductModel> productModelRepository, IBaseRepository<PurchaseOrder> purchaseOrderRepository)
        {
            _productModelRepository = productModelRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
        }

        /// <summary>
        /// 采购添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<object>> Handle(PurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            var apiResult = new ApiResult<object>();

            // 1. 创建采购单实体
            var purchaseOrder = new PurchaseOrder
            {
                PurchaseOrderNumber = request.PurchaseOrderNumber,
                SupplierName = request.SupplierName,
                ContactPerson = request.ContactPerson,
                Phone = request.Phone,
                ReceiveDate = request.ReceiveDate,
                AssociatedorderNumber = request.AssociatedorderNumber,
                BillType = request.BillType,
                CustomerName = request.CustomerName,
                Maker = request.Maker,
                Remark = request.Remark,
                MakeTime = DateTime.UtcNow,

            };

            // 2. 验证产品ID是否存在
            var productIds = request.Products.Select(p => p.ProductId).ToList();
            var existingProducts = await _productModelRepository.GetAll()
                .Where(p => productIds.Contains(p.ProductId))
                .Select(p => p.ProductId)
                .ToListAsync(cancellationToken);

            var invalidProductIds = productIds.Except(existingProducts).ToList();
            // 3. 创建中间表关联记录
            foreach (var productDto in request.Products)
            {
                purchaseOrder.Products.Add(new PurchaseOrderProduct
                {
                    ProductId = productDto.ProductId,
                    Quantity = productDto.Quantity,
                    UnitPrice = productDto.UnitPrice,
                    TotalPrice = productDto.Quantity * productDto.UnitPrice,

                });
            }

            // 4. 事务保存
            try
            {
                _purchaseOrderRepository.Add(purchaseOrder);
                apiResult.Code = (ApiEnums)Renum.添加成功;
                apiResult.Message = Renum.添加成功.ToString();
                return apiResult;
            }
            catch (Exception ex)
            {
                // 回滚事务（如果使用DbContext事务）
                apiResult.Code = (ApiEnums)Renum.添加失败;
                apiResult.Message = $"添加失败: {ex.Message}";
                return apiResult;
            }
        }
    }
}
